<!doctype html>
<script>
if (window.testRunner)
    testRunner.dumpAsText();

var TESTS = [
    ["#000", 0, 0, 0],
    ["#001", 0, 0, 17],
    ["#012", 0, 17, 34],
    ["#123", 17, 34, 51],
    ["#0001", 0, 0, 0, 17],
    ["#0012", 0, 0, 17,34],
    ["#0123", 0, 17, 34, 51],
    ["#1234", 17, 34, 51, 68],
    ["#000000", 0, 0, 0],
    ["#000012", 0, 0, 18],
    ["#001234", 0, 18, 52],
    ["#123456", 18, 52, 86],
    ["#00000000", 0, 0, 0, 0],
    ["#00000012", 0, 0, 0, 18],
    ["#00001234", 0, 0, 18, 52],
    ["#00123456", 0, 18, 52, 86],
    ["#12345678", 18, 52, 86, 120],
    // Bad content from here on shows the red failure color.
    ["#12x3", 255, 0, 0],
    ["#123x", 255, 0, 0],
    ["#123x4567", 255, 0, 0],
    ["#1234567r", 255, 0, 0],
    ["#123456x6", 255, 0, 0],
];

function extractComponents(rgbValue) {
    var re = /rgba?\((\d+),\s(\d+),\s(\d+)(,\s([\d\.]+))?\)/;
    var match = re.exec(rgbValue);
    var results = [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])];
    if (match[5])
        results.push(Math.round(parseFloat(match[5]) * 255));
    return results;
}

function componentsMatch(components, expectedR, expectedG, expectedB, expectedA) {
    if (components[0] == expectedR && components[1] == expectedG && components[2] == expectedB) {
        if (components.length != 4)
            return true;
        return components[3] == expectedA;
    }
}

function componentsAsRGBA(r, g, b, a) {
    if (a !== undefined)
        return "red:" + r + " green: " + g + " blue: " + b + " alpha: " + a;
    return "red:" + r + " green: " + g + " blue: " + b;
}

function runTest() {
    var element = document.querySelector("p");
    var results = "";

    for (var test of TESTS) {
        element.style.color = test[0];
        var components = extractComponents(window.getComputedStyle(element).color);
        if (componentsMatch(components, test[1], test[2], test[3], test[4]))
            results += "PASS " + test[0] + " was " + componentsAsRGBA(test[1], test[2], test[3], test[4]) + "<br>";
        else
            results += "FAIL " + test[0] + " should be " + componentsAsRGBA(test[1], test[2], test[3], test[4]) + " but was " + componentsAsRGBA(components[0], components[1], components[2], components[3]) + "<br>";

        // Force a color reset and style recalc.
        element.style.color = "red";
        computedStyle = window.getComputedStyle(element).color;
    }

    document.querySelector("div").innerHTML = results;
}

window.addEventListener("load", runTest, false);
</script>
<div id="results"></div>
<p></p>
